<template>
  <view class="address-edit">
    <customHeader class="address-edit-title" :title="pageTitle" />
    <view class="info-item">
      <view class="info-item-title">
        收货人
      </view>
      <input
        v-model="username"
        class="info-item-inpcontent"
        :maxlength="10"
        placeholder="请输入收货人姓名"
        @input="handleGetNameInpValue"
        @focus="handleInpOperate('FOCUS', 'username', 'isNameFocused')"
        @blur="handleInpOperate('BLUR', 'username', 'isNameFocused')"
      />
      <image
        v-if="isShowClearBtn('username', 'isNameFocused')"
        class="info-item-icon"
        src="@/assets/icon/clear-btn.png"
        @tap="handleClear('username')"
      />
    </view>
    <view class="info-item">
      <view class="info-item-title">
        手机号码
      </view>
      <input
        v-model="phone"
        class="info-item-inpcontent"
        :maxlength="11"
        placeholder="请输入11位手机号"
        @input="handleGetPhoneInpValue"
        @focus="handleInpOperate('FOCUS', 'phone', 'isPhoneFocused')"
        @blur="handleInpOperate('BLUR', 'phone', 'isPhoneFocused')"
      />
      <image
        v-if="isShowClearBtn('phone', 'isPhoneFocused')"
        class="info-item-icon"
        src="@/assets/icon/clear-btn.png"
        @tap="handleClear('phone')"
      />
      <view v-show="phoneErr" class="error">
        手机格式不正确
      </view>
    </view>
    <view class="info-item">
      <view class="info-item-title"> 城市 </view
      ><view class="info-item-content" @tap="handleShowModal">
        <view v-if="!district_id" class="content-desc">
          选择省市区
        </view>
        <view v-else class="content-title">
          {{ province_name + city_name + district_name }}
        </view>
        <view class="info-item-icon" />
      </view>
    </view>
    <view class="info-item">
      <view class="info-item-title">
        详细地址
      </view>
      <input
        v-model="desc_address"
        class="info-item-inpcontent"
        placeholder="如道路、门牌号、小区等"
        @input="handleGetAdressInpValue"
        @focus="handleInpOperate('FOCUS', 'desc_address', 'isAddressFocused')"
        @blur="handleInpOperate('BLUR', 'desc_address', 'isAddressFocused')"
      />
      <image
        v-if="isShowClearBtn('desc_address', 'isAddressFocused')"
        class="info-item-icon"
        src="@/assets/icon/clear-btn.png"
        @tap="handleClear('desc_address')"
      />
      <view v-show="addressErr" class="error">
        详细地址不得小于5个字
      </view>
    </view>
    <finish-button
      class="save-address"
      :class="{ dis: canSubmit }"
      :width="690"
      @click="handleAdd"
    >
      保存
    </finish-button>
    <actionSheet
      :is-opened-modal.sync="isShowCity"
      :height="932"
      :is-show-title="true"
      modal-title="请选择省市区"
      class="cascade-selection"
    >
      <cascade-selection
        :is-show-campus="isShowCity"
        :list="currentList"
        :campus-stack="campusStack"
        :city-info="currentSource"
        :is-full-campus="isFullCampus"
        @change="handleChange"
        @toggle="handleToggle"
      />
    </actionSheet>
  </view>
</template>

<script>
import "./index.scss";
import Taro from "@tarojs/taro";
import finishButton from "_c/finish-button/index";
import actionSheet from "_c/action-sheet/index";
import cascadeSelection from "_c/cascade-selection/index";
import { address_empty } from "@/libs/image-url";
import { address, addAddress, editAddress, districts } from "_api/mine";
import { debounce } from "@/libs/util";
import customHeader from "@/components/custom-header";

const operation = [addAddress, editAddress];
const NAME_REG = /[^\u4E00-\u9FA5a-zA-Z\d]/g;
const PHONE_REG = /^1[3-9]\d{9}$/g;
const MAX_STACK_LEN = 3;
export default {
  name: "AddressEdit",
  components: {
    finishButton,
    actionSheet,
    cascadeSelection,
    customHeader
  },
  data() {
    return {
      address_empty,
      username: "",
      phone: "",
      desc_address: "",
      isNameFocused: false,
      isPhoneFocused: false,
      isAddressFocused: false,
      phoneErr: false,
      addressErr: false,
      isShowCity: false,
      campusStack: [],
      listIndex: 0,
      isEdit: 0,
      currentList: [],
      city_id: null,
      city_name: "",
      district_id: null,
      district_name: "",
      province_id: null,
      province_name: "",
      pageTitle: ""
    };
  },
  computed: {
    /**是否显示清除按钮 */
    isShowClearBtn() {
      return function(key, subkey) {
        return this.$data[key] && this.$data[subkey];
      };
    },
    /**当前展示的索引列表 */
    // currentList() {
    //   return this.listStack[this.listIndex];
    // },
    currentSource() {
      return this.campusStack[this.listIndex];
    },
    /**校区是否为全填写 */
    isFullCampus() {
      return this.campusStack.length === MAX_STACK_LEN;
    },
    canSubmit() {
      return (
        !this.username ||
        !this.phone ||
        !this.desc_address ||
        this.phoneErr ||
        this.addressErr
      );
    }
  },
  onLoad(opt) {
    this.isEdit = ~~opt.isEdit;
    this.pageTitle = this.isEdit ? "编辑地址" : "添加地址";
    this.isEdit && this.getAddress();
  },
  methods: {
    getAddress() {
      address()
        .then(({ data }) => {
          let {
            created_at,
            deleted_at,
            student_id,
            id,
            detail_name,
            updated_at,
            ...obj
          } = data;
          Object.assign(this.$data, obj);
          this.campusStack = [
            {
              id: obj.province_id,
              province_id: obj.province_id,
              address_code: obj.province_id,
              title: obj.province_name
            },
            {
              id: obj.city_id,
              province_id: obj.province_id,
              address_code: obj.city_id,
              title: obj.city_name
            },
            {
              id: obj.district_id,
              province_id: obj.province_id,
              city_id: obj.city_id,
              address_code: obj.district_id,
              title: obj.district_name
            }
          ];
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
        });
    },
    handleAdd() {
      operation[this.isEdit]({
        username: this.username,
        phone: this.phone,
        desc_address: this.desc_address,
        province_id: this.province_id,
        city_id: this.city_id,
        district_id: this.district_id
      })
        .then(r => {
          Taro.showToast({
            title: "保存成功",
            icon: "none",
            duration: 2000
          });
          Taro.navigateBack({
            delta: 1
          });
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
        });
    },
    /**姓名输入的特殊处理 */
    handleGetNameInpValue: debounce(function({ detail: { value } }) {
      /**只能输入中英文、数字 */
      this.username = value.replace(NAME_REG, "");
    }),
    /**电话输入的特殊处理 */
    handleGetPhoneInpValue: debounce(function({ detail: { value } }) {
      this.phoneErr = !PHONE_REG.test(value);
      console.log(this.phoneErr);
      // this.phone = ~~value.replace(PHONE_REG, "");
    }),
    handleGetAdressInpValue: debounce(function({ detail: { value } }) {
      this.addressErr = value.length < 5;
    }),
    handleInpOperate(type, key, subkey) {
      if (type === "FOCUS") return (this.$data[subkey] = true);
      !this.$data[key] && (this.$data[subkey] = false);
    },
    /**清除输入 */
    handleClear(key) {
      this.$data[key] = "";
    },
    async handleShowModal() {
      this.currentList = this.district_id
        ? await this.getDistricts(3, this.province_id, this.city_id)
        : await this.getDistricts(1);
      this.isShowCity = true;
    },
    async handleChange(data) {
      /**修改校区选择 */
      if (data.type === "modify") {
        this.campusStack.splice(MAX_STACK_LEN - 1, 1, data);
        this.isShowCity = false;
        this.district_id = this.campusStack[2].address_code;
        this.district_name = this.campusStack[2].title;
      }
      if (this.campusStack.length >= MAX_STACK_LEN) return;
      this.campusStack.push(data);
      /**只存在城市时才请求区级接口 */

      switch (data.type) {
        case "FIRST":
          this.currentList = await this.getDistricts(
            2,
            this.campusStack[0].province_id
          );
          this.listIndex = 0;
          break;
        case "SECOND":
          this.currentList = await this.getDistricts(
            3,
            this.campusStack[1].province_id,
            this.campusStack[1].city_id
          );
          this.listIndex = 1;
          break;
        case "THIRD": // 选完校区后该关闭弹窗
          this.isShowCity = false;
          this.city_id = this.campusStack[1].address_code;
          this.city_name = this.campusStack[1].title;
          this.district_id = this.campusStack[2].address_code;
          this.district_name = this.campusStack[2].title;
          this.province_id = this.campusStack[0].address_code;
          this.province_name = this.campusStack[0].title;
          this.listIndex = 2;
        default:
          break;
      }
    },
    async handleToggle(index) {
      this.listIndex = index;
      console.log(index);
      // if (this.campusStack.length >= MAX_STACK_LEN) return;
      switch (index) {
        case 0:
          this.currentList = await this.getDistricts(1);
          break;
        case 1:
          this.currentList = await this.getDistricts(
            2,
            this.campusStack[0].province_id
          );
        default:
          break;
      }
      this.campusStack = this.campusStack.slice(0, index);
    },
    async getDistricts(levels, province_id, city_id) {
      let { data } = await districts({ levels, province_id, city_id });
      return data || [];
    }
  }
};
</script>
